using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace HQLAddin.Util
{
	public interface IOutputPaneLogger
	{
		void Log(string message);
		void Log(string format, params object[] args);
	}

	[Export(typeof(IOutputPaneLogger))]
	internal class OutputPaneLogger : IOutputPaneLogger
	{
		private static readonly Guid LoggerGuid = new Guid("F37A1920-1CC2-4CA8-A041-DA3312A33E2B");
		private const string LoggerName = "HqlAddin";

		private readonly IVsOutputWindow outputWindow;

		[ImportingConstructor]
		public OutputPaneLogger()
			: this((IVsOutputWindow)Package.GetGlobalService(typeof(SVsOutputWindow)))
		{}

		public OutputPaneLogger(IVsOutputWindow outputWindow)
		{
			if (outputWindow == null) throw new ArgumentNullException("outputWindow");
			this.outputWindow = outputWindow;
		}

		public void Log(string message)
		{
			var pane = GetOrCreatePane();
			if (pane == null) return;

			if (ErrorHandler.Failed(pane.OutputString(message)))
			{
				return;
			}
		}

		public void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		private IVsOutputWindowPane GetOrCreatePane()
		{
			Guid loggerGuid = LoggerGuid;
			IVsOutputWindowPane pane;

			if (ErrorHandler.Failed(outputWindow.GetPane(ref loggerGuid, out pane)) || pane == null)
			{
				if (!ErrorHandler.Failed(outputWindow.CreatePane(ref loggerGuid, LoggerName, 1, 0)))
				{
					if (ErrorHandler.Failed(outputWindow.GetPane(ref loggerGuid, out pane)) || pane == null)
					{
						return null;
					}
				}else
				{
					return null;
				}
			}
			return pane;
		}
	}
}

